/**
 * Created by Allen on 2016/7/15.
 */
package com.dandelion.api;

import com.rockit.core.http.HttpClientProperties;
import com.rockit.core.http.HttpClientService;
import com.rockit.core.http.HttpRequest;
import com.rockit.core.http.HttpResponse;
import com.rockit.core.utils.JacksonUtil;

import java.util.List;

public class TestMain {
    static HttpClientService service = new HttpClientService(new HttpClientProperties());
//    public static void main(String[] args) {
//        StringBuilder builder = new StringBuilder(1024*100);
//        request("103101", 1, builder);
//        request("101101", 1, builder);
//        System.out.println(builder.toString());
//    }

    private static void request(String code, int level, StringBuilder builder) {
        if (level >= 4) {
            return;
        }

        if (level == 2) {
                //if (!("104104101".equals(code) || "104104103".equals(code) || "104104106".equals(code))) {
            //    return;
            //}
        }

        String url = "http://gensvr-n.vip.com/address/address?areaid=%s";
        String realUrl = String.format(url, code);
        HttpRequest request = HttpRequest.get(realUrl);

        HttpResponse response = service.execute(request);
        String text = response.getBody();
        Rsp rsp = JacksonUtil.toObject(text, Rsp.class);
        String sql = "insert into t_address_tree(parent_code,code,name,create_time)values('%s','%s','%s',now());";
        if (rsp != null && rsp.getList() != null && rsp.getList().size() > 0) {
            rsp.getList().forEach(area -> {
                if (area == null || "0".equals(area.getId())) {
                    return;
                }
                String output = String.format(sql, code, area.getId(), area.getName());

                builder.append(output).append("\n");
                request(area.id, level + 1, builder);
            });
        }
    }

    public static class Rsp {
        List<Area> list;

        public List<Area> getList() {
            return list;
        }

        public void setList(List<Area> list) {
            this.list = list;
        }
    }

    public static class Area {
        private String id;
        private String name;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
